let db              = require('../db/dbmanager');
const constants     = require('../data/constants');
const log4js        = require('../data/log');
var format          = require('string-format');
const logger        = log4js.getLogger('db');

/**
 * 设备表操作
 */
let Camera = {
    /**
     * 插入数据
     * @param {*} data ["testcamera",false]
     */
    insert:function(data,callback){
        if(!data.deviceid){
            callback(null);
            return;
        }
        let param ={
            $deviceid:data.deviceid,
            $password:data.password,
            $online  :data.online,
            $last_heart: (new Date()).getTime()
        };
        const sql = "insert into CAMERA(deviceid,password,online,last_heart) values($deviceid,$password,$online,$last_heart)";

        db.sqliteDB.run(sql,param);
        db.sqliteDB.lastRow("CAMERA",(d)=>{
            callback(d);
        });
    },
    /**
     * 更新内容,newdata的属性有; online,deviceid,sip_command_host,sip_command_port,sumnum,version,device_type,last_heart
     * @param {*} newdata 
     */
    update:function(newdata,callback){
        let sqldata={
            $deviceid: newdata.deviceid
        };
        
        let newsql='';
        if(newdata.online){
            sqldata.$online = newdata.online;
            if(newsql)newsql+=',';
            newsql += "online=$online";
        }
        if(newdata.sip_command_host){
            sqldata.$sip_command_host = newdata.sip_command_host;
            if(newsql)newsql+=',';
            newsql += "sip_command_host=$sip_command_host";
        }
        if(newdata.sip_command_port){
            sqldata.$sip_command_port = newdata.sip_command_port;
            if(newsql)newsql+=',';
            newsql += "sip_command_port=$sip_command_port";
        }
        if(newdata.sumnum){
            sqldata.$sumnum = newdata.sumnum;
            if(newsql)newsql+=',';
            newsql += "sumnum=$sumnum";
        }
        if(newdata.version){
            sqldata.$version = newdata.version;
            if(newsql)newsql+=',';
            newsql += "version=$version";
        }
        if(newdata.device_type){
            sqldata.$device_type = newdata.device_type;
            if(newsql)newsql+=',';
            newsql += "device_type=$device_type";
        }
        
        if(newdata.camera_name){
            sqldata.$camera_name = newdata.camera_name;
            if(newsql)newsql+=',';
            newsql += "camera_name=$camera_name";
        }
        if(newdata.last_heart){
            sqldata.$last_heart=newdata.last_heart;
            if(newsql)newsql+=',';
            newsql += "last_heart=$last_heart";
        }
        
        const sql = "update CAMERA set " + newsql + " where deviceid=$deviceid";
        logger.info(sql);
        db.sqliteDB.run(sql,sqldata);
        if(callback){
            callback(newdata);
        }
    },
    del:function(deviceid){
        let param={
            $deviceid: deviceid
        };
        const sql = "DELETE FROM CAMERA WHERE deviceid=$deviceid";
        db.sqliteDB.run(sql,param);
        const sqlDevice="DELETE FROM DEVICE WHERE parentid = $parentid";
        param={$parentid:deviceid};
        db.sqliteDB.run(sqlDevice,param);
        console.log(sql,sqlDevice);
    },
    /**
     * 
     * @param {string} deviceid 通道号
     * @param {*} callback 
     */
    getCameraByDeviceId:function(deviceid,callback){
        const sql = "SELECT * FROM CAMERA WHERE deviceid=$deviceid";
        db.sqliteDB.all(sql,{$deviceid:deviceid},function(err,rows){
            if(!err){
                callback(rows);
            }else{
                callback();
            }
        });
    },
    /**
     * 设备设置的在线状态
     * @param {*} deviceid 
     * @param {*} callback 
     */
    updateOnline:function(deviceid,online,callback){
        let me = this;
        me.getCameraByDeviceId(deviceid,(ret)=>{
            constants.registry[deviceid].online=online;
            if(online){
                constants.registry[deviceid].last_heart=(new Date()).getTime();
            }
            if(ret.length){
                me.update(constants.registry[deviceid],(d)=>{
                    if(callback){
                        callback(deviceid);
                    }
                });
            }else{
                me.insert(constants.registry[deviceid],(d)=>{
                    if(callback){
                        callback(deviceid);
                    }
                });
            }
        });
    },
    /**
     * 查询列表
     * @param {*} page 第几页
     * @param {*} size 每页大小
     */
    list:function(page,size){
        let p = new Promise(function(resolve,reject){
            const sql = format("SELECT * from CAMERA order by deviceid DESC limit {0} offset {0}*{1}", size, page);
            logger.info('camera list', sql);
            db.sqliteDB.queryData(sql,function(rows){
                resolve(rows);
            });
        });
        return p;
    },
    count:function(){
        let p = new Promise(function(resolve,reject){
            let sql = "SELECT COUNT(*) as c FROM CAMERA";
            db.sqliteDB.oneData(sql,(ret)=>{
                logger.info('camera count ret',ret)
                resolve(ret.c)
            });
        });
        return p;
    },
    // TODO: 重置状态，camera的可能要修改
    reset:function(){
        let minTime = (new Date()).getTime()-60*3*1000;
        let sql = "UPDATE CAMERA SET online=0 WHERE last_heart < " + minTime;
        db.sqliteDB.run(sql);
    }
};

module.exports = Camera;